/*
 * @Author: wangtao
 * @Date: 2021-02-18 11:21:01
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-05-20 10:54:08
 * @Description: 一键申请
 */
import React from 'react';
import {
  StyleSheet,
  Image,
  SafeAreaView,
  ScrollView,
  Platform,
  BackHandler,
  NativeModules
} from 'react-native';
import {
  iconApplyGoldInsurance,
  iconApplyGrayInsurance,
  leftBack
} from '@/images';
import { XMVehicleKeyBord, msg, ValidConst } from '@/common';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  screenWidth
} from '@/styles';
import api from '@/api';
import Picker from '../../../common/picker';
import Quotation from './components/quotation';
import Remark from './components/remark';
import RechargeHeader from '../../../components/RechargeHeader';

export default class InsuranceApply extends React.Component {
  static navigationOptions = () => ({
    title: '申请',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconApplyGoldInsurance : iconApplyGrayInsurance}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      activeTab: 1,
      isVisible: false,
      carTypeOptions: [], // 车型选项
      carType: '', // 选择的车辆类型
      carNo: '', // 车牌号
      insureLinkMan: '', // 投保联系人
      insureLinkPhone: '', // 联系电话
    };
  }

  componentDidMount() {
    // 获取所有车辆类型
    this.getAllCarType();
    // 处理安卓物理返回键
    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    } else {
      NativeModules.BridgeManager.iOSIQKeyaboard(true);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    } else {
      NativeModules.BridgeManager.iOSIQKeyaboard(false);
    }
  }

  onBackAndroid = () => {
    Picker.hide();
    msg.emit('router: back');
    return true;
  };

  render() {
    const {
      activeTab,
      isVisible,
      carNo,
      carType,
      insureLinkMan,
      insureLinkPhone,
    } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <RechargeHeader
          style={{ backgroundColor: mainBgColorWhite }}
          leftBackStyle={{ backgroundColor: 'rgba(0,0,0,0.1)' }}
          leftBackIcon={leftBack}
          leftTitle='一键申请'
        />
        <ScrollView
          contentContainerStyle={styles.scrollContainer}
          showsVerticalScrollIndicator={false}
        >
          <Image
            source={require('../../../images/insurance/insurance_banner.png')}
            resizeMode='stretch'
            style={styles.bannerImg}
          />
          {/* 申请表单 */}
          <Quotation
            activeTab={activeTab}
            onChange={this.onChange}
            showPicker={this.showPicker}
            applicationInsurance={this.applicationInsurance}
            carNo={carNo}
            carType={carType}
            insureLinkMan={insureLinkMan}
            insureLinkPhone={insureLinkPhone}
          />
          {/* 提示 */}
          <Remark />
          {/* 车牌键盘 */}
          <XMVehicleKeyBord
            isVisible={isVisible}
            onKeyDown={this.onKeyDown}
            onKeyDelete={this.onKeyDelete}
            onClose={() => this.setState({ isVisible: false })}
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  // 一键申请<下一步>
  applicationInsurance = () => {
    const {
      activeTab,
      carTypeOptions,
      carType,
      carNo,
      insureLinkMan,
      insureLinkPhone,
    } = this.state;
    // 条件验证

    if (!carType) {
      msg.emit('app:tip', { text: '车辆种类必填' });
      return;
    }
    if (!insureLinkMan) {
      msg.emit('app:tip', { text: '投保联系人必填' });
      return;
    }
    if (!insureLinkPhone) {
      msg.emit('app:tip', { text: '投保人联系方式必填' });
      return;
    }
    if (!ValidConst.phone.test(insureLinkPhone)) {
      msg.emit('app:tip', { text: '请输入正确的手机号' });
      return;
    }
    if (activeTab == 1) {
      if (!carNo) {
        msg.emit('app:tip', { text: '车牌号货或发动机号必填' });
        return;
      }
    }

    const carTypeObj = carTypeOptions.find((item) => {
      if (item.name == carType) {
        return true;
      }
    });

    let params;
    // 有号牌
    if (activeTab == 1) {
      params = {
        carNo,
        carType: carTypeObj,
        insureLinkMan,
        insureLinkPhone,
        isHaveCarNo: 'Y',
      };
    } else {
      params = {
        carType: carTypeObj,
        insureLinkMan,
        insureLinkPhone,
        isHaveCarNo: 'N',
      };
    }

    api.insurance.applicationInsurance(params).then((res) => {
      if (res.success) {
        this.setState({
          carNo: '',
          carType: '',
          insureLinkMan: '',
          insureLinkPhone: '',
        });
        msg.emit('router: goToNext', {
          routeName: 'InsuranceApplyForm',
          applicationNo: res.data.applicationNo,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取所有车辆类型
  getAllCarType = () => {
    api.insurance.getAllCarType().then((res) => {
      if (res.data) {
        this.setState({ carTypeOptions: res.data });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  showPicker = (title, dataList, pickerType) => {
    const { carTypeOptions, carType } = this.state;
    if (carTypeOptions.length <= 0) return;
    const options = carTypeOptions.map((item) => {
      return item.name;
    });
    let selectedCarType = carType || (options[0] ? options[0] : '');
    Picker.init({
      pickerTitleText: '选择车辆种类',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [selectedCarType],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: options,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        console.log(
          '🚀🚀🚀wimi======>>>pickedValue, pickedIndex',
          pickedValue,
          pickedIndex,
        );
        this.setState({ carType: pickedValue[0] });
      },
      onPickerCancel: (pickedValue, pickedIndex) => { },
      onPickerSelect: (pickedValue, pickedIndex) => { },
    });
    Picker.show();
  };

  onChange = (key, val) => {
    this.setState({ [key]: val });
  };

  onKeyDown = (item) => {
    const { carNo } = this.state;
    const reg = /^[\u4e00-\u9fa5]/;
    if (reg.test(carNo) && carNo.length >= 7) {
      return;
    }
    this.setState({ carNo: carNo + item });
  };

  onKeyDelete = () => {
    const { carNo } = this.state;
    this.setState({ carNo: carNo.slice(0, -1) });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
  scrollContainer: {
    alignItems: 'center',
  },
  bannerImg: {
    width: screenWidth,
    height: px2dp(420),
  },
});
